package eu.testing.system.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import eu.testing.system.dao.AssignedDao;
import eu.testing.system.models.Assigned;
import eu.testing.system.models.AssignedTest;

public class AssignedDaoImpl extends SimpleJdbcDaoSupport implements
		AssignedDao {
	private static final String SQL_SELECT = "SELECT * FROM assigned WHERE USERNAME = ?";
	private static final String SQL_DELETE = "DELETE FROM assigned WHERE USERNAME = ?";
	private static final String SQL_DELETE_INT = "DELETE FROM assigned WHERE TEST_ID = ?";
	private static final String SQL_INSERT = "INSERT INTO assigned (USERNAME, TEST_ID) VALUES (?, ?)";

	@Override
	public void insertAssigned(AssignedTest as) {
		for (Assigned assigned : as.getPairs()) {
			getSimpleJdbcTemplate().update(SQL_INSERT, assigned.getUser(),
					assigned.getTestId());
		}

	}

	@Override
	public void deleteAssigned(String username) {
		getSimpleJdbcTemplate().update(SQL_DELETE, username);

	}

	@Override
	public List<Assigned> getAssigned(String username) {
		List<Assigned> assigned = getSimpleJdbcTemplate().query(SQL_SELECT,
				new AssignedParameterizedRowMapper(), username);
		return assigned;

	}

	public class AssignedParameterizedRowMapper implements
			ParameterizedRowMapper<Assigned> {
		@Override
		public Assigned mapRow(ResultSet rs, int rowNum) throws SQLException {
			Assigned as = new Assigned(rs.getString("USERNAME"),
					rs.getInt("TEST_ID"));

			return as;
		}

	}

	@Override
	public void deleteAssigned(int id) {
		getSimpleJdbcTemplate().update(SQL_DELETE_INT, id);
		
	}

}
